package com.xian.cloud.controller;

import com.xian.cloud.api.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @Author: xlr
 * @Date: Created in 5:33 PM 2019/8/23
 */
@Slf4j
@RestController
public class TestController {

    public static final String URL_SERVER = "cloud-nacos-server";

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Autowired
    Client client;

    /**
     * loadBalancerClient
     * @return
     */
    @GetMapping("/test")
    public String test() {
        // 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
        ServiceInstance serviceInstance = loadBalancerClient.choose(URL_SERVER);
        String url = serviceInstance.getUri() + "/hello?name=" + "alibaba";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        return "Invoke : " + url + ", return : " + result;
    }

    /**
     * web
     * @return
     */
    @GetMapping("/test/web")
    public Mono<String> testWeb() {
        Mono<String> result = webClientBuilder.build()
                .get()
                .uri("http://"+URL_SERVER+"/hello?name=alibaba")
                .retrieve()
                .bodyToMono(String.class);
        return result;
    }


    /**
     * fegin
     * @return
     */
    @GetMapping("/test/fegin")
    public String testFegin() {
        String result = client.hello("alibaba");
        return "Return : " + result;
    }

}
